package com.molyfun.parents.view.zhibo;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.im.MyConnectionListener;
import com.molyfun.parents.rest.BaseResponse;
import com.molyfun.parents.rest.bean.ZhiboRoomResponse;
import com.molyfun.parents.view.TwoTabBar;
import com.molyfun.parents.view.ZhiboTwoTabBar;
import com.molyfun.parents.view.common.MfEditText;
import com.molyfun.parents.zhibo.im.ZhiboStrMsgRequest;
import com.molyfun.parents.zhibo.impl.IZhiboIns;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMManager;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:10/18/16.
 */
public class ZhiboControlView extends FrameLayout implements View.OnClickListener, TwoTabBar.TwoBarClickListener {

    protected LayoutInflater layoutInflater;

    private static final int ZhiboMsgSendTypeNormal = 1001;
    private static final int ZhiboMsgSendTypeAsk = 1002;

    private int mCurrentSendType = ZhiboMsgSendTypeNormal;

    private Context context;

    //    @InjectView(R.id.switch_camera)
//    ImageButton mSwitchCamera;
    @InjectView(R.id.base_title_left)
    ImageView mLeave;
    @InjectView(R.id.rtc_request_btn)
    ImageView mRtcRequest;
//    @InjectView(R.id.push_get_material_btn)
//    Button mGetPushMaterialBtn;

    @InjectView(R.id.zhibo_title)
    TextView mZhiboTitle;
    @InjectView(R.id.zhibo_share)
    ImageView mZhiboShare;

    @InjectView(R.id.send_edt)
    MfEditText mSendEdt;
    @InjectView(R.id.send)
    TextView mSend;
    //    @InjectView(R.id.web_view)
//    WebView mWebview;

//    @InjectView(R.id.msgQuenView)
//    LinearLayout mMessagQuenView;
//    @InjectView(R.id.input_bottom)
//    LinearLayout mInputBottom;
//    @InjectView(R.id.bottom_operation_layout)
//    RelativeLayout mBottomOperationLayout;
//    @InjectView(R.id.ic_scale)
//    ImageView mIcScale;
    @InjectView(R.id.show_controll_view)
    View mShowControllView;
    @InjectView(R.id.refresh_stream)
    ImageView mRefreshStream;


    @InjectView(R.id.zhibo_title_layout)
    RelativeLayout mZhiboTitleLayout;
    @InjectView(R.id.bottom_layout)
    LinearLayout mZhiboBottomLayout;

    @InjectView(R.id.zhibo_two_tabbar)
    ZhiboTwoTabBar mZhiboTwoTabBar;

    private TIMConversation conversation;

    MyConnectionListener myConnectionListener;

    private IZhiboIns mIZhiboIns;

//    protected GetSubjectResponse.SubjectDetailBean mSubjectDetailBean;

    private String mZhiboId, mZhiboName;

    private ZhiboRoomResponse.RoomBean mRoomBean;

    public ZhiboControlView(Context context, AttributeSet attrs, int defStyle) {
        this(context, attrs);
    }

    public ZhiboControlView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public ZhiboControlView(Context context) {
        super(context);
        init(context, null);
    }

    private int mCurrentRtcState = RtcState.RtcStateNormal;

    private ZhiboControlViewShowCallback mZhiboControlViewShowCallback;

    public interface ZhiboControlViewShowCallback{
        void onZhiboControlViewVisibleChange(boolean isShow);
    }

    public void setZhiboControlViewShowCallback(ZhiboControlViewShowCallback zhiboControlViewShowCallback){
        this.mZhiboControlViewShowCallback = zhiboControlViewShowCallback;
    }

    public interface RtcState {
        int RtcStateNormal = 1001;
        int RtcStateApply = 1002;
        int RtcStateRtcing = 1003;
    }

    private void init(Context context, AttributeSet attrs) {
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
        layoutInflater.inflate(R.layout.widget_zhibo_controller, this);
        ButterKnife.inject(this);
        mLeave.setOnClickListener(this);
        mRtcRequest.setOnClickListener(this);
        mZhiboShare.setOnClickListener(this);
        mShowControllView.setOnClickListener(this);

        mZhiboTwoTabBar.initData("聊天", "提问");
        mZhiboTwoTabBar.setTwoBarClickListener(this);

        mSend.setOnClickListener(this);
        mRefreshStream.setOnClickListener(this);
        mHandler.sendEmptyMessageDelayed(EVENT_HIDE_BAR, CONTANT_HIDE_TIME_LENGTH);
        mSendEdt.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    if(mHandler.hasMessages(EVENT_HIDE_BAR)){
                        mHandler.removeMessages(EVENT_HIDE_BAR);
                    }
                }else{
                    if(!mHandler.hasMessages(EVENT_HIDE_BAR)){
                        mHandler.sendEmptyMessageDelayed(EVENT_HIDE_BAR, CONTANT_HIDE_TIME_LENGTH);
                    }
                }
            }
        });
    }

    /**
     * init view
     */
    public void initData(TIMConversation timConversation, IZhiboIns iZhiboIns, String zhiboId, String zhiboName, MyConnectionListener myConnectionListener) {
        this.conversation = timConversation;
        this.mIZhiboIns = iZhiboIns;
        this.mZhiboId = zhiboId;
        this.mZhiboName = zhiboName;
//        this.mSubjectDetailBean = subjectDetailBean;
        mZhiboTitle.setText(zhiboName);
        this.myConnectionListener = myConnectionListener;
//        mRoomBean = roomBean;
    }

    public void setRtcBegin(boolean isBegin) {
        if (isBegin) {
            mCurrentRtcState = RtcState.RtcStateRtcing;
            mRtcRequest.setImageResource(R.mipmap.ic_rtc_hangup);
        } else {
            mCurrentRtcState = RtcState.RtcStateNormal;
            mRtcRequest.setImageResource(R.drawable.selector_rtc_apply);
        }
    }

    public void setShareVisiable(boolean isVisiable) {
        if (isVisiable) {
            mZhiboShare.setVisibility(View.VISIBLE);
        } else {
            mZhiboShare.setVisibility(View.GONE);
        }
    }

    @Override
    public void onTwoBarClick(int chooseTab) {
        switch (chooseTab) {
            case TwoTabBar.TwoTabChooseTab.BAR_ONE:
                mCurrentSendType = ZhiboMsgSendTypeNormal;
                break;
            case TwoTabBar.TwoTabChooseTab.BAR_TWO:
                mCurrentSendType = ZhiboMsgSendTypeAsk;
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.like_count:
                break;

//            case R.id.play:
//
//                System.out.println("play---->");
//                if (lastPushMatritalType.equals("2")) {
//                    mGameView.loadUrl("javascript:playVideo()");
//                } else {
//
//                    mGameView.loadUrl("javascript:playAudio()");
//                }
//                break;
//            case R.id.pause:
//                System.out.println("stop---->");
//                if (lastPushMatritalType.equals("2")) {
//                    mGameView.loadUrl("javascript:pauseVideo()");
//                } else {
//                    mGameView.loadUrl("javascript:pauseAudio()");
//                }
//                break;
            case R.id.zhibo_share:

                mIZhiboIns.onShare();

//                ShareDialogActivity.sharePage();
                break;
            case R.id.send:

                sendTextMessage(mSendEdt.getText().toString().trim());

                mSendEdt.setText("");

                break;

            case R.id.rtc_request_btn:
                if (mCurrentRtcState == RtcState.RtcStateNormal) {
                    sendRtcApply();
                } else if (mCurrentRtcState == RtcState.RtcStateApply) {
                    sendRtcApplyCancel();
                } else if (mCurrentRtcState == RtcState.RtcStateRtcing) {
                    setRtcBegin(false);
                    mIZhiboIns.stopConference();
                }
                break;
            case R.id.base_title_left:
                mIZhiboIns.onFinish();
                break;
            case R.id.show_controll_view:
                changeBottomBarState();
                break;
            case R.id.refresh_stream:
                mIZhiboIns.onRefreshStream();
                break;
            default:
                break;
        }
    }

    private boolean bottomBarVisibleState = true;

    public void changeBottomBarState() {
        if(mHandler.hasMessages(EVENT_HIDE_BAR)){
            mHandler.removeMessages(EVENT_HIDE_BAR);
        }
        if(bottomBarVisibleState){
            mZhiboTitleLayout.setVisibility(View.INVISIBLE);
            mZhiboBottomLayout.setVisibility(View.INVISIBLE);
            bottomBarVisibleState = false;
        }else{
            mZhiboTitleLayout.setVisibility(View.VISIBLE);
            mZhiboBottomLayout.setVisibility(View.VISIBLE);
            bottomBarVisibleState = true;
            mHandler.sendEmptyMessageDelayed(EVENT_HIDE_BAR, CONTANT_HIDE_TIME_LENGTH);

        }
        if(mZhiboControlViewShowCallback != null){
            mZhiboControlViewShowCallback.onZhiboControlViewVisibleChange(bottomBarVisibleState);
        }
    }

    private static final int EVENT_HIDE_BAR = 3001;
    private static final int CONTANT_HIDE_TIME_LENGTH = 5000;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case EVENT_HIDE_BAR:
                    if(bottomBarVisibleState){
                        changeBottomBarState();
                    }
                    break;
            }
        }
    };

    private void sendTextMessage(String content) {
        if(TextUtils.isEmpty(content.trim())){
            mIZhiboIns.showToast("不能发空消息");
        }else{
            sendNormalMsg(content);
        }
    }

    public void sendNormalMsg(String content) {

        ZhiboStrMsgRequest zhiboStrMsgRequest = new ZhiboStrMsgRequest(mZhiboId, content, mCurrentSendType == ZhiboMsgSendTypeNormal ? "msg" : "ques");
        final Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().sendMsg(zhiboStrMsgRequest);
        if(!TextUtils.isEmpty(TIMManager.getInstance().getLoginUser())) {
            call.enqueue(new Callback<BaseResponse>() {
                @Override
                public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                    if (response.body().getCode() == 200) {
                    }
                }

                @Override
                public void onFailure(Call<BaseResponse> call, Throwable t) {
                }
            });
        }else{
            myConnectionListener.showHint(new MyConnectionListener.LoginHxCallback() {
                @Override
                public void onSuccess() {
                    call.enqueue(new Callback<BaseResponse>() {
                        @Override
                        public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                            if (response.body().getCode() == 200) {
                            }
                        }

                        @Override
                        public void onFailure(Call<BaseResponse> call, Throwable t) {
                        }
                    });
                }
            });
            return;
        }

    }

    public void sendRtcApply() {

        final Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().sendRtcApply(mZhiboId);//mZhiboBean.getId());
        if(!TextUtils.isEmpty(TIMManager.getInstance().getLoginUser())) {
            call.enqueue(new Callback<BaseResponse>() {
                @Override
                public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                    if (response.body().getCode() == 200) {
                        mCurrentRtcState = RtcState.RtcStateApply;
                        mRtcRequest.setImageResource(R.drawable.selector_rtc_apply_cancel);
//                    sendRtcMsg("apply");
                    }
                }

                @Override
                public void onFailure(Call<BaseResponse> call, Throwable t) {
                }
            });
        }else{
            myConnectionListener.showHint(new MyConnectionListener.LoginHxCallback() {
                @Override
                public void onSuccess() {
                    call.enqueue(new Callback<BaseResponse>() {
                        @Override
                        public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                            if (response.body().getCode() == 200) {
                                mCurrentRtcState = RtcState.RtcStateApply;
                                mRtcRequest.setImageResource(R.drawable.selector_rtc_apply_cancel);
//                    sendRtcMsg("apply");
                            }
                        }

                        @Override
                        public void onFailure(Call<BaseResponse> call, Throwable t) {
                        }
                    });
                }
            });
            return;
        }

    }

    public void sendRtcApplyCancel() {

        Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().sendRtcApplyCancel(mZhiboId);//mZhiboBean.getId());
        call.enqueue(new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                if (response.body().getCode() == 200) {
                    mCurrentRtcState = RtcState.RtcStateNormal;
                    mRtcRequest.setImageResource(R.drawable.selector_rtc_apply);
//                    sendRtcMsg("apply");
                }
            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {
            }
        });

    }

}